<?php
/**
 * 解析财务报表-数据入库
 *（Logic）
 */
namespace App\Logic\Amazon\Api\Parse;

use App\Models\Amazon\FbaSettlementDepositDetail;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysICountry;
use App\Models\SalesReport\FBADeposit;
class GetV2SettlementReportDataFlatFileV2
{
    public static function exe($lines,$accountId,$needId = 0){

        if(!$accountId)return 2;
        if(!is_array($lines))return 2;
        ini_set('memory_limit', '512M');
        set_time_limit(0);
        $i = 0;
        $count = 0;
        try{
            //汇总
            $parentData = $lines[0]; //集合中的首条数据（汇总数据）
            $FbaDeposit = FBADeposit::query()->where('settlement_id',$parentData['settlement-id'])->first();
            if ($FbaDeposit) return true;
            $flag = self::_saveSettlementDeposit($parentData,$accountId,$needId);
            $flag && $count++;
            $i++;

            //明细
            unset($lines[0]); //过滤掉集合中的首条数据，剩下即为明细数据
            foreach($lines as $k => $line){
                FbaSettlementDepositDetail::query()->where('order_id',$line['order-id'])->delete(); //清除明细旧数据

                //更新
                self::saveSettlementDepositDetail($line,$accountId,$parentData);
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * 添加SettlementDeposit
     * @param $line
     * @param $accountId
     * @param $needId
     * @return bool
     */
    private static function _saveSettlementDeposit($line,$accountId,$needId){
        if (!$line['settlement-id']) return true;
        $count = FBADeposit::query()->where('settlement_id', $line['settlement-id'])->count();
        if ($count > 0) return true;
        $currency = strtoupper($line['currency']);
        if ($currency == 'EUR') {
            $countryId = FBADeposit::$_EURCountryId;
            $areaId = SysArea::getSysAreaIdByArea('EU');
        } else {
            $countryId = AmazonCountry::getCountryIdByCurrencyCode($currency);
            $countryId = $countryId ?: 0;
            $areaId = SysICountry::getAreaIdByCountryId($countryId);
        }
        $depositDate = gmdate('Y-m-d H:i:s', strtotime($line['deposit-date']));

        $re = FBADeposit::query()->updateOrCreate([
                'settlement_id' => $line['settlement-id']
            ],[
                'account_id' => $accountId,
                'area_id' => $areaId,
                'country_id' => $countryId,
                'report_load_id' => $needId,
                'settlement_sdate' => gmdate('Y-m-d H:i:s', strtotime($line['settlement-start-date'])),
                'settlement_edate' => gmdate('Y-m-d H:i:s', strtotime($line['settlement-end-date'])),
                'deposit_date' => $depositDate,
                'total_amount' => $line['total-amount'] ?? 0,
                'currency' => $currency,
                'rate_odds' => ExchangeRate::getRateOddsToRMB($currency, strtotime($depositDate)),
            ]);

        return $re ? false : true;
    }

    //private static $_match = [
    //    'Previous Reserve Amount Balance' => 'pre_reserve_amount_balance',
    //    'Current Reserve Amount' => 'cur_reserve_amount'
    //];

    /**
     * 更新SettlementDeposit
     * @param $line
     * @param $accountId
     * @param $parentData
     * @return bool
     */
    //private static function _updateSettlementDeposit($line){
    //    if (!$line['settlement-id']) return true;
    //    $re = FBADeposit::query()->where('settlement_id', $line['settlement-id'])->first();
    //    if (!$re) return true;
    //    dd($line);
    //    if (!array_key_exists($line['amount-description'], self::$_match)) {
    //        if ($re->country_id == FBADeposit::$_EURCountryId) {
    //            $countryId = FBADeposit::getEUCountryId($line['marketplace-name']);
    //            if ($countryId) {
    //                $re->country_id = $countryId;
    //                $reFlag = $re->save();
    //                return !$reFlag ? false : true;
    //            }
    //        }
    //        return true;
    //    } else {
    //        if ($re->country_id == FBADeposit::$_EURCountryId) {
    //            $countryId = FBADeposit::getEUCountryId($line['marketplace-name']);
    //            if ($countryId) {
    //                $re->country_id = $countryId;
    //            }
    //        }
    //        $re->{self::$_match[$line['amount-description']]} = $line['amount'];
    //        $reFlag = $re->save();
    //        return !$reFlag ? false : true;
    //    }
    //}

    public static function saveSettlementDepositDetail($line,$accountId,$parentData){

        $depositDate = gmdate('Y-m-d H:i:s',strtotime($parentData['deposit-date'])); //创建日期
        $settlementStartdate = gmdate('Y-m-d H:i:s',strtotime($parentData['settlement-start-date'])); //结算开始时间
        $settlementEnddate = gmdate('Y-m-d H:i:s',strtotime($parentData['settlement-end-date'])); //结算结束时间

        FbaSettlementDepositDetail::query()->create([
            'settlement_id'         => $parentData['settlement-id'],
            'order_id'              => $line['order-id'],
            'sku'                   => $line['sku'],
            'account_id'            => $accountId,
            'settlement_sdate'      => $settlementStartdate,
            'settlement_edate'      => $settlementEnddate,
            'deposit_date'          => $depositDate,
            'transaction_type'      => $line['transaction-type'],
            'merchant_order_id'     => $line['merchant-order-id'],
            'adjustment_id'         => $line['adjustment-id'],
            'shipment_id'           => $line['shipment-id'],
            'marketplace_name'      => $line['marketplace-name'],
            'amount_type'           => $line['amount-type'],
            'amount_description'    => $line['amount-description'],
            'amount'                => $line['amount'],
            'fulfillment_id'        => $line['fulfillment-id'],
            'posted_date'           => gmdate('Y-m-d H:i:s', strtotime($line['posted-date'])),
            'posted_date_time'      => gmdate('Y-m-d H:i:s',strtotime($line['posted-date-time'])),
            'order_item_code'       => $line['order-item-code'],
            'merchant_order_item_id'      => $line['merchant-order-item-id'],
            'merchant_adjustment_item_id' => $line['merchant-adjustment-item-id'],
            'quantity_purchased'    => $line['quantity-purchased'],
            'promotion_id'          => $line['promotion-id']
        ]);
    }

}

/*namespace App\Logic\Amazon\Api\Parse;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysICountry;
use App\Models\SalesReport\FBADeposit;

class GetV2SettlementReportDataFlatFileV2
{
    public static function exe($lines, $accountId)
    {
        if (!$accountId) return 2;
        if (!is_array($lines)) return 2;
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        $i = 0;
        $count = 0;
        try {
            foreach ($lines as $k => $line) {
                if ($k == 0) {
                    $flag = self::_addSettlementDeposit($line, $accountId);
                    $flag && $count++;
                } else {
                    $flag = self::_upSettlementDeposit($line);
                    $flag && $count++;
                }
                $i++;
            }
        } catch (\Exception $e) {
            report($e);
        }
        return $i == $count ? 1 : 2;
    }


    private static $_match = [
        'Previous Reserve Amount Balance' => 'pre_reserve_amount_balance',
        'Current Reserve Amount' => 'cur_reserve_amount'
    ];

    private static function _addSettlementDeposit($line, $accountId)
    {
        if (!$line['settlement-id']) return true;
        $count = FBADeposit::query()->where('settlement_id', $line['settlement-id'])->count();
        if ($count > 0) return true;
        $currency = strtoupper($line['currency']);
        if ($currency == 'EUR') {
            $countryId = FBADeposit::$_EURCountryId;
            $areaId = SysArea::getSysAreaIdByArea('EU');
        } else {
            $countryId = AmazonCountry::getCountryIdByCurrencyCode($currency);
            $countryId = $countryId ?: 0;
            $areaId = SysICountry::getAreaIdByCountryId($countryId);
        }
        $depositDate = gmdate('Y-m-d H:i:s', strtotime($line['deposit-date']));
        $re = FBADeposit::query()->create([
            'settlement_id' => $line['settlement-id'],
            'account_id' => $accountId,
            'area_id' => $areaId,
            'country_id' => $countryId,
            'settlement_sdate' => gmdate('Y-m-d H:i:s', strtotime($line['settlement-start-date'])),
            'settlement_edate' => gmdate('Y-m-d H:i:s', strtotime($line['settlement-end-date'])),
            'deposit_date' => $depositDate,
            'total_amount' => $line['total-amount'],
            'currency' => $currency,
            'rate_odds' => ExchangeRate::getRateOddsToRMB($currency, strtotime($depositDate)),
        ]);
        return !$re ? false : true;
    }

    private static function _upSettlementDeposit($line)
    {
        if (!$line['settlement-id']) return true;
        $re = FBADeposit::query()->where('settlement_id', $line['settlement-id'])->first();
        if (!$re) return true;
        if (!array_key_exists($line['amount-description'], self::$_match)) {
            if ($re->country_id == FBADeposit::$_EURCountryId) {
                $countryId = FBADeposit::getEUCountryId($line['marketplace-name']);
                if ($countryId) {
                    $re->country_id = $countryId;
                    $reFlag = $re->save();
                    return !$reFlag ? false : true;
                }
            }
            return true;
        } else {
            if ($re->country_id == FBADeposit::$_EURCountryId) {
                $countryId = FBADeposit::getEUCountryId($line['marketplace-name']);
                if ($countryId) {
                    $re->country_id = $countryId;
                }
            }
            $re->{self::$_match[$line['amount-description']]} = $line['amount'];
            $reFlag = $re->save();
            return !$reFlag ? false : true;
        }
    }
}*/
